package com.example.annasbook.controller;

import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.annasbook.model.BookModelVo;
import com.example.annasbook.model.BookPageQry;
import com.example.annasbook.repository.convert.BookConvert;
import com.example.annasbook.repository.entity.BookEntity;
import com.example.annasbook.service.BookService;
import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@RequestMapping("bookinfo")
public class Index {
    private final JobLauncher jobLauncher;

    private final BookService bookService;

    private final BookConvert convert;

    private final Job booklistjob;
    @GetMapping("/saveBook")
    public ExitStatus saveBook() throws Exception {
        JobParameters jobParameters = new JobParametersBuilder()
                .addLong("date",new Date().getTime())
                .toJobParameters();
        JobExecution jobExecution = jobLauncher.run(booklistjob, jobParameters);
        return jobExecution.getExitStatus();
    }

    @PostMapping("/page")
    public PageResult<BookModelVo> page(@RequestBody @Validated BookPageQry qry) throws Exception {
        Page<BookEntity> page = bookService.page(new Page<>(qry.getPageNo(), qry.getPageSize()));
        PageResult<BookModelVo> bookModelVos = new PageResult<>();
        if(page.getRecords().isEmpty()){
            return bookModelVos;
        }
        List<BookModelVo> collect = page.getRecords().stream().map(convert::BookModelVo).collect(Collectors.toList());
        bookModelVos.setTotal((int) page.getTotal());
        bookModelVos.addAll(collect);
        return bookModelVos;
    }
}
